const HealthExaminationModel = require('../models/healthExamination.model');
const AdlAssessmentModel = require('../models/adlAssessment.model');
const AncillaryExamModel = require('../models/ancillaryExam.model');
const HospitalizationHistoryModel = require('../models/hospitalizationHistory.model');
const FamilyBedHistoryModel = require('../models/familyBedHistory.model');
const MedicationModel = require('../models/medication.model');
const VaccinationHistoryModel = require('../models/vaccinationHistory.model');
const HealthAbnormalitiesModel = require('../models/healthAbnormalities.model');
const pool = require('../config/database');

class CheckupService {
  /**
   * 过滤健康体检数据，只保留数据库表中存在的字段
   * @param {Object} healthExaminationData - 前端传来的健康体检数据
   * @returns {Object} 过滤后的数据
   */
  static filterHealthExaminationFields(healthExaminationData) {
    // 定义数据库表中实际存在的字段
    const validFields = [
      'da_id', 'tjrq', 'zrys_id', 'zzbm', 'zzqt', 'tw', 'ml', 'hxpl',
      'xyssyz', 'xyszyz', 'xyssyy', 'xyszyy', 'sg', 'tz', 'yw', 'tzzs',
      'lnrjkztzp', 'lnrzlnlzp', 'lnrrzgn', 'rzgnzf', 'lnrqgzt', 'qgztzf',
      'tydlpl', 'mcdlsj', 'jcdlsj', 'dlfs', 'ysxg', 'xyzk', 'rxyl', 'ksxynl',
      'jynl', 'yjpl', 'ryjl', 'sfjj', 'jjnl', 'ksyjnl', 'jynnsfzj', 'yjzl',
      'yjzlqtmc', 'zybwhysjcs', 'gzzl', 'cysj', 'dwfc', 'dwfcbhcs', 'dwfcfhcsmc',
      'dwfswz', 'dwfswzbhcs', 'dwfswzbhcsmc', 'dwwlys', 'dwwlysbhcs', 'dwwlysbhcsmc',
      'dwhxwz', 'dwhxwzbhcs', 'dwhxwzbhcsmc', 'dwqt', 'dwqtbhcs', 'dwqtbhcsmc',
      'kcbm', 'clbm', 'clbz1', 'clbz2', 'clbz3', 'clbz4', 'clbz5', 'clbz6',
      'clbz7', 'clbz8', 'clbz9', 'clbz10', 'clbz11', 'clbz12', 'ybbm',
      'zysl', 'zyjzsl', 'yysl', 'yyjzsl', 'tlbm', 'ydgnbm', 'ydbm', 'ydyc',
      'pfbm', 'pfqt', 'gmbm', 'gmqt', 'lbjbm', 'lbjqt', 'tzxbm', 'hxybm',
      'hxyqt', 'lybm', 'lyqt', 'xzpl', 'xlbm', 'xzzybm', 'xzzymc', 'fbytbm',
      'fbytmc', 'fbbkbm', 'fbbkmc', 'fbgdbm', 'fbgdmc', 'fbpdbm', 'fbpdmc',
      'ydxzybm', 'ydxzymc', 'xzszbm', 'zbdmbdbm', 'gmzzbm', 'gmzzqt', 'rxbm',
      'rxqt', 'fkwybm', 'fkwyycmc', 'yindbm', 'yindycmc', 'fkgjbm', 'fkgjycmc',
      'fkgtbm', 'fkgtycmc', 'fkfjbm', 'fkfjycmc', 'fkqt', 'nxgjbbm', 'nxgjbqtmc',
      'szjbbm', 'szjbqtmc', 'xzjbbm', 'xzjbqtmc', 'xgjbbm', 'xgjbqtmc',
      'ybjbbm', 'ybjbqtmc', 'sjxtjbbm', 'sjxtjbqtmc', 'qtxtjbbm', 'qtxtjbqtmc',
      'jkpjbm', 'jkpjzc', 'jkzdbm', 'jkzdqt', 'wxyskzbm', 'qtjy', 'jtzmb',
      'jyjzym', 'jkzd', 'xctjrq', 'sfbjgtj', 'qttjjg'
    ];
    
    // 过滤数据，只保留有效字段
    const filteredData = {};
    for (const field of validFields) {
      if (healthExaminationData.hasOwnProperty(field)) {
        filteredData[field] = healthExaminationData[field];
      }
    }
    
    return filteredData;
  }

  /**
   * 创建完整的体检记录
   * @param {Object} checkupData - 体检数据
   * @returns {Promise<Object>} 创建的体检记录
   */
  static async createCheckup(checkupData) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      // 1. 过滤健康体检数据，只保留数据库表中存在的字段
      const filteredHealthExamination = this.filterHealthExaminationFields(checkupData.healthExamination);
      
      // 2. 创建主体检记录
      const mainExamination = await HealthExaminationModel.create(filteredHealthExamination);
      const tjId = mainExamination.tj_id; // 注意这里应该是 tj_id 而不是 id
      
      const results = {
        healthExamination: mainExamination,
        adlAssessment: null,
        ancillaryExam: null,
        hospitalizationHistory: [],
        familyBedHistory: [],
        medication: [],
        vaccinationHistory: [],
        healthAbnormalities: []
      };
      
      // 3. 创建ADL评估记录（如果存在）
      if (checkupData.adlAssessment) {
        const adlData = { ...checkupData.adlAssessment, tj_id: tjId };
        results.adlAssessment = await AdlAssessmentModel.create(adlData);
      }
      
      // 4. 创建辅助检查记录（如果存在）
      if (checkupData.ancillaryExam) {
        const ancillaryData = { ...checkupData.ancillaryExam, tj_id: tjId };
        results.ancillaryExam = await AncillaryExamModel.create(ancillaryData);
      }
      
      // 5. 批量创建住院史记录
      if (checkupData.hospitalizationHistory && checkupData.hospitalizationHistory.length > 0) {
        const hospitalizationData = checkupData.hospitalizationHistory.map(item => ({
          ...item,
          tj_id: tjId
        }));
        results.hospitalizationHistory = await HospitalizationHistoryModel.createBatch(hospitalizationData);
      }
      
      // 6. 批量创建家庭病床史记录
      if (checkupData.familyBedHistory && checkupData.familyBedHistory.length > 0) {
        const familyBedData = checkupData.familyBedHistory.map(item => ({
          ...item,
          tj_id: tjId
        }));
        results.familyBedHistory = await FamilyBedHistoryModel.createBatch(familyBedData);
      }
      
      // 7. 批量创建用药记录
      if (checkupData.medication && checkupData.medication.length > 0) {
        const medicationData = checkupData.medication.map(item => ({
          ...item,
          tj_id: tjId
        }));
        results.medication = await MedicationModel.createBatch(medicationData);
      }
      
      // 8. 批量创建预防接种史记录
      if (checkupData.vaccinationHistory && checkupData.vaccinationHistory.length > 0) {
        const vaccinationData = checkupData.vaccinationHistory.map(item => ({
          ...item,
          tj_id: tjId
        }));
        results.vaccinationHistory = await VaccinationHistoryModel.createBatch(vaccinationData);
      }
      
      // 9. 批量创建健康评价异常记录
      if (checkupData.healthAbnormalities && checkupData.healthAbnormalities.length > 0) {
        const abnormalityData = checkupData.healthAbnormalities.map(item => ({
          ...item,
          tj_id: tjId
        }));
        results.healthAbnormalities = await HealthAbnormalitiesModel.createBatch(abnormalityData);
      }
      
      await connection.commit();
      
      return {
        success: true,
        message: '体检记录创建成功',
        data: results
      };
      
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }
  
  /**
   * 获取完整的体检记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<Object>} 完整的体检记录
   */
  static async getCompleteCheckup(tjId) {
    try {
      const results = {};
      
      // 获取主体检记录
      results.healthExamination = await HealthExaminationModel.findById(tjId);
      if (!results.healthExamination) {
        throw new Error('体检记录不存在');
      }
      
      // 获取相关记录
      const [adlAssessment, ancillaryExam, hospitalizationHistory, familyBedHistory, medication, vaccinationHistory, healthAbnormalities] = await Promise.all([
        AdlAssessmentModel.findByTjId(tjId),
        AncillaryExamModel.findByTjId(tjId),
        HospitalizationHistoryModel.findByTjId(tjId),
        FamilyBedHistoryModel.findByTjId(tjId),
        MedicationModel.findByTjId(tjId),
        VaccinationHistoryModel.findByTjId(tjId),
        HealthAbnormalitiesModel.findByTjId(tjId)
      ]);
      
      results.adlAssessment = adlAssessment[0] || null;
      results.ancillaryExam = ancillaryExam[0] || null;
      results.hospitalizationHistory = hospitalizationHistory;
      results.familyBedHistory = familyBedHistory;
      results.medication = medication;
      results.vaccinationHistory = vaccinationHistory;
      results.healthAbnormalities = healthAbnormalities;
      
      return {
        success: true,
        data: results
      };
      
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 更新体检记录
   * @param {number} tjId - 体检ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<Object>} 更新结果
   */
  static async updateCheckup(tjId, updateData) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const results = {};
      
      // 更新主体检记录
      if (updateData.healthExamination) {
        results.healthExamination = await HealthExaminationModel.update(tjId, updateData.healthExamination);
      }
      
      // 更新ADL评估记录
      if (updateData.adlAssessment) {
        const existingAdl = await AdlAssessmentModel.findByTjId(tjId);
        if (existingAdl.length > 0) {
          results.adlAssessment = await AdlAssessmentModel.update(existingAdl[0].id, updateData.adlAssessment);
        } else {
          const adlData = { ...updateData.adlAssessment, tj_id: tjId };
          results.adlAssessment = await AdlAssessmentModel.create(adlData);
        }
      }
      
      // 更新辅助检查记录
      if (updateData.ancillaryExam) {
        const existingAncillary = await AncillaryExamModel.findByTjId(tjId);
        if (existingAncillary.length > 0) {
          results.ancillaryExam = await AncillaryExamModel.update(existingAncillary[0].id, updateData.ancillaryExam);
        } else {
          const ancillaryData = { ...updateData.ancillaryExam, tj_id: tjId };
          results.ancillaryExam = await AncillaryExamModel.create(ancillaryData);
        }
      }
      
      await connection.commit();
      
      return {
        success: true,
        message: '体检记录更新成功',
        data: results
      };
      
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }
  
  /**
   * 删除体检记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<Object>} 删除结果
   */
  static async deleteCheckup(tjId) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      // 删除所有相关记录
      await Promise.all([
        AdlAssessmentModel.deleteByTjId(tjId),
        AncillaryExamModel.deleteByTjId(tjId),
        HospitalizationHistoryModel.deleteByTjId(tjId),
        FamilyBedHistoryModel.deleteByTjId(tjId),
        MedicationModel.deleteByTjId(tjId),
        VaccinationHistoryModel.deleteByTjId(tjId),
        HealthAbnormalitiesModel.deleteByTjId(tjId)
      ]);
      
      // 删除主体检记录
      const result = await HealthExaminationModel.delete(tjId);
      
      await connection.commit();
      
      return {
        success: true,
        message: '体检记录删除成功',
        data: { deleted: result }
      };
      
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }
  
  /**
   * 获取体检记录列表
   * @param {Object} params - 查询参数
   * @returns {Promise<Object>} 体检记录列表
   */
  static async getCheckupList(params = {}) {
    try {
      const { page = 1, limit = 10, daId, startDate, endDate, ...filters } = params;
      
      const result = await HealthExaminationModel.findAll({
        page,
        limit,
        daId,
        startDate,
        endDate,
        ...filters
      });
      
      return {
        success: true,
        data: result.data,
        pagination: {
          page: result.page,
          limit: result.limit,
          total: result.total,
          totalPages: result.totalPages
        }
      };
      
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 获取体检统计信息
   * @param {Object} params - 查询参数
   * @returns {Promise<Object>} 统计信息
   */
  static async getCheckupStats(params = {}) {
    try {
      const { daId, startDate, endDate } = params;
      
      // 这里可以添加更多统计逻辑
      const stats = {
        totalCheckups: 0,
        completedCheckups: 0,
        pendingCheckups: 0,
        abnormalityRate: 0
      };
      
      return {
        success: true,
        data: stats
      };
      
    } catch (error) {
      throw error;
    }
  }
}

module.exports = CheckupService;